package com.chuangjiangx.member.common.utils.AIFace;

import com.alibaba.fastjson.JSONObject;
import com.chuangjiangx.commons.ConvertUtils;
import com.chuangjiangx.member.common.utils.AppHttpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.util.*;


/**
 * Created by chuangjiangzqq on 2018/9/13.
 */
public class AiClient implements IAiClient{

    private static final Logger log = LoggerFactory.getLogger(AiClient.class);


    public <T extends AiResponse> AiResponse execute(@NotNull AiRequest<T> request)  {
        if(request == null) {
            throw new AiRequestParamsNoExitsException("1001","请求参数为空");
        }
        String resp;
        String dataResp;
        AiResponse _aiResponse = new AiResponse();
        try{
            Map<String,String> requestMap = ConvertUtils.objectToMap(request, false);
            resp = AppHttpService.sendPost(request.getServerUrl(), buildPayParamss(requestMap).toString());
        }catch(Exception e){
            log.error("AI网络请求出错" + e);
            throw new AiNetErrorException("0001","AI网络请求出错");
        }
        try{
            _aiResponse.setErrorCode(JacksonUtils.jsonToPojo(resp,AiResponse.class).getErrorCode());
            if (!AIConstant.CODE_SUCCESS.equals(_aiResponse.getErrorCode())) {
                _aiResponse.setErrorMsg(JSONObject.parseObject(resp).get("error_msg").toString());
            } else {
                _aiResponse.setErrorMsg(JacksonUtils.jsonToPojo(resp,AiResponse.class).getErrorMsg());
            }
            dataResp = JacksonUtils.ObjectToJson(JacksonUtils.jsonToPojo(resp,AiResponse.class).getData());
            if(!StringUtils.isBlank(dataResp) && !"null".equals(dataResp)){
                _aiResponse.setData(JacksonUtils.jsonToPojo(dataResp,request.getResponseClass()));
            }
        }catch(Exception e){
            log.error("JSON格式转换异常" + e);
            throw new AiResponseFormatErrorException("1002","JSON格式转换异常");
        }
        return _aiResponse;
    }


    public static StringBuilder buildPayParamss(Map<String, String> payParams) {
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList keys = new ArrayList(payParams.keySet());
        Collections.sort(keys);
        for(Iterator var4 = keys.iterator(); var4.hasNext(); stringBuilder.append("&")) {
            String key = (String)var4.next();
            stringBuilder.append(key).append("=");
            stringBuilder.append(payParams.get(key));
        }
        stringBuilder.setLength(stringBuilder.length() - 1);
        return stringBuilder;
    }
    }

